package com.gym.fileserver.service.impl;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.twt.common.exceptions.AppException;
import com.twt.common.utils.MD5Util;
import com.gym.fileserver.service.FileServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FileServerServiceImpl implements FileServerService {
    private final String fileSavePath = "./upload";
    private final long maxSize = 1024 * 1024 * 5;
    private final List whiteFile = Lists.newArrayList();

    {
        whiteFile.add("image/png");
        whiteFile.add("image/jpeg");
    }

    private final Map<String, String> contentTypeMap = new HashMap<>(16);

    {
        contentTypeMap.put("image/png", ".png");
        contentTypeMap.put(".png", "image/png");

        contentTypeMap.put("image/jpeg", ".jpg");
        contentTypeMap.put(".jpg", "image/jpeg");


    }

    @Override
    public String uploadFile(MultipartFile file) {
        this.checkFile(file);

        if (!FileUtil.exist(fileSavePath)) {
            if (FileUtil.isDirectory(fileSavePath)) {
                FileUtil.mkdir(fileSavePath);
            }
        }

        String filename = file.getOriginalFilename();
        String contentType = file.getContentType();


        String encode = MD5Util.encode(filename);
        String saveFileName = encode + contentTypeMap.get(contentType);

        if (FileUtil.exist(new File(saveFileName))) {
            return saveFileName;
        }

        try {
            FileUtil.writeFromStream(file.getInputStream(), new File(returnFilePath(saveFileName)));
        } catch (IOException e) {
            log.error("文件上传失败,{}", e.getMessage());
            throw new AppException("文件保存失败!");
        }

        return saveFileName;
    }

    @Override
    public void downloadFile(HttpServletResponse response, String fileName) {
        int index = fileName.lastIndexOf(".");
        String sub = fileName.substring(index);
        String contentType = contentTypeMap.get(sub);

        response.setContentType(contentType);

        File file = new File(returnFilePath(fileName));
        if (!FileUtil.isEmpty(file)) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);

                int len = 0;
                byte bytes[] = new byte[1024];
                while ((len = fileInputStream.read(bytes)) > 0) {
                    response.getOutputStream().write(bytes, 0, len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void checkFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new AppException("上传的文件为空");
        }
        if (file.getSize() > maxSize) {
            throw new AppException("文件大小最大为5M");
        }
        String contentType = file.getContentType();

        log.debug("contentType:{}", contentType);

        if (!whiteFile.contains(contentType)) {
            throw new AppException(String.format("%s文件类型不允许", contentType));
        }
    }

    private String returnFilePath(String saveFileName) {
        return fileSavePath + File.separator + saveFileName;
    }
}
